<template>
  <div v-if="permissionsLists(81)">
    <!-- 头部 -->
    <page-header :title="$t('m.Program_list')" :has-return="false">
      <el-button
        type="primary"
        @click="addProgram()"
        v-if="permissionsLists(84)"
      >
        {{ $t('m.Add_program_list') }}
      </el-button>
    </page-header>

    <div class="container">
      <div class="list_div">
        <div
          style=" display: flex;justify-content: space-between;align-items: flex-start;"
        >
          <div class="page_list_div">
            <el-form class="page_list_top" label-position="right">
              <el-form-item
                :label="$t('m.search_') + ':'"
                class="page_list_top"
              >
                <el-input
                  :placeholder="$t('m.program_title')"
                  v-model="params.search"
                  prefix-icon="el-icon-search"
                  clearable
                />
              </el-form-item>

              <el-form-item
                :label="$t('m.invite_Type') + ':'"
                class="page_list_top"
              >
                <el-select
                  v-model="params.fileType"
                  :placeholder="$t('m.pleaseChoose')"
                  ref="select1"
                  @change="searchBtn(1)"
                >
                  <el-option
                    v-for="item in options1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item
                :label="$t('m.Delivery_status') + ':'"
                class="page_list_top"
              >
                <el-select
                  v-model="params.deliveryState"
                  :placeholder="$t('m.pleaseChoose')"
                  ref="select2"
                  @change="searchBtn(2)"
                >
                  <el-option
                    v-for="item in options2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="page_list_top page_list_search">
                <el-button
                  class="search_button reset_button"
                  @click="searchBtn()"
                >
                  {{ $t('m.search_') }}</el-button
                >
              </el-form-item>
              <el-form-item class="page_list_top">
                <el-button class="reset_button" @click="refreshBtn">
                  {{ $t('m.refresh') }}</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div class="page_list_div" v-if="permissionsLists(224)">
            <el-form class="page_list_top" label-position="right">
              <el-form-item class="page_list_top" style="margin-right:0;">
                <el-button class="reset_button" @click="batchDalete">
                  {{ $t('m.Delete_program_batch') }}</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
        <el-divider class="el_divider"></el-divider>
        <div class="el_table_div">
          <!--表格-->
          <el-table
            :data="playerLists"
            :row-key="getPlayId"
            ref="playId"
            @selection-change="handlePlayId"
          >
            <emptydata slot="empty" v-if="playerLists.length == 0" />
            <el-table-column
              type="selection"
              width="56"
              :reserve-selection="true"
              fixed="left"
            >
            </el-table-column>
            <el-table-column
              :label="$t('m.program_title')"
              prop="title"
              fixed
              min-width="150"
            />
            <el-table-column
              :label="$t('m.invite_Type')"
              show-overflow-tooltip
              min-width="150"
            >
              <template #default="scope">
                {{ scope.row.fileType | valFormat(options1) }}
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('m.Program_content')"
              prop=""
              min-width="300"
            >
              <template #default="scope">
                <span v-for="item in scope.row.urls" :key="item">
                  <span v-if="scope.row.fileType == 1"
                    ><el-image
                      :src="fileUrlFormat(item)"
                      alt=""
                      :preview-src-list="[fileUrlFormat(item)]"
                      class="el_img"
                      fit="cover"
                  /></span>
                  <span v-if="scope.row.fileType == 2" class="video_span">
                    <video :src="fileUrlFormat(item)" class="el_video"></video>
                    <img
                      src="@/assets/imgs/ic_play@2x.png"
                      alt=""
                      class="el_video_img"
                      v-show="scope.row.fileType == 2"
                      @click="playVideo(item)"
                    />
                  </span>
                </span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('m.Numb_of_stations')" min-width="150">
              <template #default="scope">
                {{
                  scope.row.deliveryCount
                    ? scope.row.deliveryCount.totalCount
                    : 0
                }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('m.Delivery_status')" min-width="150">
              <template #default="scope">
                <span v-if="scope.row.deliveryState == 1">
                  <div>
                    {{ $t('m.uploadSuccess') }}:
                    {{ scope.row.deliveryCount.successCount }}
                  </div>
                  <div>
                    {{ $t('m.uploadFailure') }}:
                    {{ scope.row.deliveryCount.failureCount }}
                  </div>
                </span>
                <span
                  v-else
                  :style="
                    scope.row.deliveryState == 2
                      ? 'color:#4ce48a;'
                      : scope.row.deliveryState == 0
                      ? 'color:#ffc855;'
                      : 'color:#ff605a;'
                  "
                >
                  {{ scope.row.deliveryState | valFormat(options2) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('m.Delivery_date')" min-width="180">
              <template #default="scope">
                {{ scope.row.deliveryTime | dateformat }}
              </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column
              :label="$t('m.Users_Details_Operation')"
              width="108"
              fixed="right"
              v-if="isArrayEqual([84, 204, 205, 224], permissionsLists)"
            >
              <template #default="scope">
                <el-dropdown>
                  <img
                    src="@/assets/imgs/ic_operation.svg"
                    alt=""
                    class="dropdown_img"
                  />
                  <el-dropdown-menu
                    slot="dropdown"
                    style="white-space: nowrap !important;"
                  >
                    <span>
                      <el-dropdown-item
                        v-if="permissionsLists(204)"
                        @click.native="getDetail(scope.row)"
                        >{{ $t('m.Details') }}</el-dropdown-item
                      >
                      <el-dropdown-item
                        v-if="permissionsLists(84)"
                        @click.native="addProgram(scope.row)"
                        >{{ $t('m.branch_Edit') }}</el-dropdown-item
                      >
                      <el-dropdown-item
                        @click.native="issueAds(scope.row)"
                        v-if="permissionsLists(205) && scope.row.deliveryCount"
                        >{{ $t('m.Deliver_advertisement') }}</el-dropdown-item
                      >
                      <el-dropdown-item
                        @click.native="deletePlayBtn(scope.row)"
                        v-if="permissionsLists(224)"
                        >{{ $t('m.Delete_play') }}</el-dropdown-item
                      >
                    </span>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            :total="total"
            :current="params.pageNum"
            :size="params.pageSize"
            @changePageSize="handleSizeChange"
            @changePageNum="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 下发广告 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="issueDialog"
      :title="$t('m.Select_station')"
      width="930px"
      top="150px"
      append-to-body
      @close="cancelBtn"
    >
      <div class="container" style="padding:0;min-width:0;margin:0;">
        <div class="list_div">
          <div class="page_list_div" style="padding:0;">
            <el-form class="page_list_top" label-position="right">
              <el-form-item class="page_list_top">
                <el-input
                  :placeholder="$t('m.Station_List_placeholder')"
                  v-model="cabinetParams.search"
                  prefix-icon="el-icon-search"
                  clearable
                />
              </el-form-item>

              <el-form-item
                :label="$t('m.Delivery_status') + ':'"
                class="page_list_top"
              >
                <el-select
                  v-model="cabinetParams.deliveryState"
                  :placeholder="$t('m.pleaseChoose')"
                >
                  <el-option
                    v-for="item in options4"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="page_list_top page_list_search">
                <el-button
                  class="search_button reset_button"
                  @click="clickSearch()"
                >
                  {{ $t('m.search_') }}</el-button
                >
              </el-form-item>
              <el-form-item class="page_list_top">
                <el-button class="reset_button" @click="clickReset">
                  {{ $t('m.refresh') }}</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div class="el_table_div" style="padding:0;">
            <el-table
              :data="cabinetList"
              max-height="440px"
              style="width:100%;"
              :row-key="getStationId"
              ref="adsId"
              @selection-change="handleSelectionChange"
            >
              <emptydata slot="empty" v-if="cabinetList.length == 0" />
              <el-table-column type="selection" width="56"> </el-table-column>
              <el-table-column
                :label="$t('m.Station_SN')"
                prop="cabinetNo"
                min-width="104"
              />
              <el-table-column
                :label="'IMEI'"
                prop="imei"
                show-overflow-tooltip
                min-width="166"
              >
              </el-table-column>
              <el-table-column
                :label="$t('m.Shop_Details_Franchisee')"
                prop="agentName"
                min-width="135"
              >
                <template #default="scope">
                  {{ scope.row.agentName | strFormat }}
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('m.Shop_name')"
                prop="branchName"
                min-width="135"
              >
                <template #default="scope">
                  {{ scope.row.branchName | strFormat }}
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('m.status')"
                prop="cabinetNo"
                min-width="135"
              >
                <template #default="scope">
                  {{ scope.row.state | valFormat(options3) | strFormat }}
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('m.Delivery_status')"
                prop="cabinetNo"
                min-width="135"
              >
                <template #default="scope">
                  <span
                    :style="
                      scope.row.deliveryState == 1
                        ? 'color:#4ce48a;'
                        : scope.row.deliveryState == 0
                        ? 'color:#ffc855;'
                        : 'color:#ff605a;'
                    "
                  >
                    {{ scope.row.deliveryState | valFormat(options4) }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelBtn" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button
          class="cancel_btn confirm_btn"
          :style="formList.imeiList.length == 0 ? 'opacity: 0.5;' : ''"
          :disabled="formList.imeiList.length == 0"
          @click="confirmBtn()"
          >{{ $t('m.Deliver_advertisement') }}</el-button
        >
      </span>
    </el-dialog>

    <!-- 查看视频 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="playDialog"
      :title="$t('m.play_video')"
      width="640px"
      append-to-body
      @close="closePlay"
    >
      <div class="el_dialog_center">
        <video
          :src="fileUrlFormat(urlVideo)"
          controls="controls"
          autoplay="autoplay"
          class="play_video"
        ></video>
      </div>
    </el-dialog>

    <!-- 删除节目单 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="deleteDialog"
      :title="
        deleteType == 2 ? $t('m.Delete_program_batch') : $t('m.Delete_play')
      "
      width="560px"
      append-to-body
    >
      <div class="dialog_content">
        <div class="dialog_content1">
          {{ $t('m.Delete_play_hint') }}
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialog = false" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button @click="deleteBtn" class="cancel_btn confirm_btn">{{
          $t('m.confirm_')
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import share from '../../mixins/share'
// import PageHeader from '../../common/module/page-header.vue'
import pagination from '@/components/pagination.vue'

export default {
  components: { pagination },
  // mixins: [share],
  data () {
    return {
      params: {
        advertId: '',
        search: '',
        deliveryState: '',
        fileType: '',
        pageNum: 1,
        pageSize: 10
      },
      playerLists: [],
      lang: this.$t('m'),
      total: 0,
      playDialog: false,
      urlVideo: '',
      options1: [
        { value: '', label: this.$t('m.all') },
        { value: 1, label: this.$t('m.program_img') },
        { value: 2, label: this.$t('m.program_Video') }
      ],
      options2: [
        { value: '', label: this.$t('m.all') },
        { value: 0, label: this.$t('m.Pending_deliver') },
        { value: 1, label: this.$t('m.Partially_deliver') },
        { value: 2, label: this.$t('m.Program_delivered') },
        { value: 3, label: this.$t('m.Program_Failed') }
      ],
      options3: [
        {
          value: 0,
          label: this.$t('m.Station_Status_Off')
        },
        {
          value: 1,
          label: this.$t('m.Station_Status_On')
        },
        {
          value: 3,
          label: this.$t('m.agency_activated')
        }
      ],
      options4: [
        { value: '', label: this.$t('m.all') },
        { value: 0, label: this.$t('m.Pending_deliver') },
        { value: 1, label: this.$t('m.Program_delivered') },
        { value: 2, label: this.$t('m.Program_Failed') }
      ],
      issueDialog: false,
      cabinetParams: {
        id: '',
        deliveryState: '',
        search: ''
      },
      cabinetList: [],
      formList: {
        id: '',
        imeiList: []
      },
      chooseList: {
        ids: [], //节目单ID集合
        list: [] //节目单
      },
      deleteType: '',
      itemData: '',
      deleteDialog: false,
      permissionsIds: []
    }
  },
  created () {
    this.$store.state.permissions.forEach(item => {
      this.permissionsIds.push(Number(this.$jsencrypt.decrypt(item)))
    })
    if (!this.permissionsLists(81)) {
      return
    }
    this.params = this.$cache.get('searchParams')
      ? this.$cache.get('searchParams')
      : this.params
    this.getList()
  },
  methods: {
    //权限id校验
    permissionsLists (val) {
      return this.permissionsIds.includes(val)
    },
    //播放视频
    playVideo (item) {
      this.urlVideo = item
      this.playDialog = true
    },
    //关闭视频
    closePlay () {
      this.playDialog = false
      this.urlVideo = ''
    },

    //添加-编辑节目单
    addProgram (item) {
      this.setPageNum(this.params.pageNum, this.params.pageSize, this.params)
      if (item) {
        this.$router.push({
          path: '/ads/player-create',
          query: { id: item.id }
        })
      } else {
        this.$router.push('/ads/player-create')
      }
    },

    //获取节目单详情
    getDetail (item) {
      this.setPageNum(this.params.pageNum, this.params.pageSize, this.params)
      this.$router.push({ path: '/ads/player-detail', query: { id: item.id } })
    },

    //搜索-节目单列表
    searchBtn (e) {
      this.params.pageNum = 1
      this.remPageNum()
      this.$nextTick(() => {
        e ? this.$refs[`select${e}`].blur() : ''
      })
      this.clearTable()
      this.getList()
    },

    //重置-节目单列表
    refreshBtn () {
      this.params = this.$options.data.call(this).params
      this.remPageNum()
      this.clearTable()
      this.getList()
    },

    //节目单列表
    getList () {
      this.$api.ad.getPrograms(this.params).then(res => {
        if (res.code == 0) {
          this.playerLists = res.data.records
          this.total = res.data.total
        }
      })
    },
    handleSizeChange (val) {
      this.params.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.params.pageNum = val
      this.getList()
    },

    //打开下发广告
    issueAds (item) {
      this.cabinetParams = this.$options.data.call(this).cabinetParams
      this.formList = this.$options.data.call(this).formList
      this.cabinetList = []
      this.cabinetParams.id = item.id
      this.formList.id = item.id
      this.getCabinet()
    },

    //获取节目单关联的机柜
    getCabinet () {
      this.$api.ad.getProgramsCabinet(this.cabinetParams).then(res => {
        if (res.code == 0) {
          this.cabinetList = res.data
          this.issueDialog = true
        } else {
          this.$message.error(res.message)
        }
      })
    },

    //搜索关联的机柜
    clickSearch () {
      this.getCabinet()
    },

    //重置关联的机柜
    clickReset () {
      this.cabinetParams.search = ''
      this.cabinetParams.deliveryState = ''
      this.getCabinet()
    },

    //取消下发广告
    cancelBtn () {
      this.issueDialog = false
    },

    //确认下发广告
    confirmBtn () {
      this.$api.ad.sentAds(this.formList).then(res => {
        if (res.code == 0) {
          this.$message.success(res.message)
          this.issueDialog = false
          this.getList()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 机柜imei
    getStationId (row) {
      return row.imei
    },

    // 选中的机柜
    handleSelectionChange (e) {
      this.formList.imeiList = e.map(item => item.imei)
    },

    // 清空选中的节目单
    clearTable () {
      this.chooseList = this.$options.data.call(this).chooseList
      this.$refs.playId.clearSelection()
    },

    // 节目单id
    getPlayId (row) {
      return row.id
    },

    // 选中的节目行
    handlePlayId (e) {
      this.chooseList.ids = e.map(item => item.id)
      this.chooseList.list = e
    },

    // 批量删除按钮
    batchDalete () {
      if (this.chooseList.ids.length == 0) {
        this.$message.error(this.$t('m.Delete_play_select'))
        return
      } else {
        if (this.hasPositiveValue) {
          this.deleteType = 2
          this.deleteDialog = true
        } else {
          this.batchDaletePlays()
        }
      }
    },

    // 单个删除按钮
    deletePlayBtn (item) {
      this.itemData = item
      if (
        item.deliveryCount &&
        item.deliveryCount.totalCount &&
        item.deliveryCount.totalCount > 0
      ) {
        this.deleteType = 1
        this.deleteDialog = true
      } else {
        this.deletePlays()
      }
    },

    // 单个删除
    deletePlays () {
      this.$api.ad.deletePlay(this.itemData.id).then(res => {
        if (res.code == 0) {
          this.$message.success(this.$t('m.Delete_play_succeed'))
          this.deleteDialog = false
          const deleteId = this.chooseList.ids.findIndex(
            item => item === this.itemData.id
          )
          const index = this.chooseList.list.findIndex(
            item => item.id === this.itemData.id
          )
          const indexs = this.playerLists.findIndex(
            item => item.id === this.itemData.id
          )
          if (deleteId !== -1) {
            this.chooseList.ids.splice(deleteId, 1)
          }
          if (index !== -1) {
            this.chooseList.list.splice(index, 1)
          }
          if (indexs !== -1) {
            this.playerLists.splice(indexs, 1)
          }
          if (this.chooseList.ids.length == 0) {
            this.clearTable()
          }
          let totalPage = Math.ceil((this.total - 1) / this.params.pageSize)
          this.params.pageNum =
            this.params.pageNum > totalPage ? totalPage : this.params.pageNum
          this.params.pageNum =
            this.params.pageNum < 1 ? 1 : this.params.pageNum
          this.getList()
        } else if (res.code == 22706) {
          this.$message.error(this.$t('m.Delete_play_failed'))
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 批量删除
    batchDaletePlays () {
      let params = {
        ids: this.chooseList.ids
      }
      this.$api.ad.batchDaletePlay(params).then(res => {
        if (res.code == 0) {
          this.$message.success(this.$t('m.Delete_play_succeed'))
          this.deleteDialog = false
          let totalPage = Math.ceil((this.total - 1) / this.params.pageSize)
          this.params.pageNum =
            this.params.pageNum > totalPage ? totalPage : this.params.pageNum
          this.params.pageNum =
            this.params.pageNum < 1 ? 1 : this.params.pageNum          
          this.getList()
          this.clearTable()
        } else if (res.code == 22706) {
          this.$message.error(this.$t('m.Delete_play_failed'))
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 确定删除节目单
    deleteBtn () {
      if (this.deleteType == 1) {
        this.deletePlays()
      } else if (this.deleteType == 2) {
        this.batchDaletePlays()
      }
    }
  },
  computed: {
    //是否存在机柜
    hasPositiveValue () {
      return this.chooseList.list.some(
        item =>
          item.deliveryCount &&
          item.deliveryCount.totalCount &&
          item.deliveryCount.totalCount > 0
      )
    }
  }
}
</script>
<style scoped lang="scss">
.el_img {
  max-width: 40px !important;
  height: 30px !important;
  margin: 4px;
}
.el_video {
  width: 40px !important;
  height: 30px !important;
  margin: 4px;
  position: relative;
}
.el_video::-webkit-media-controls-enclosure {
  display: none;
}
.video_span {
  position: relative;
  width: 40px !important;
  height: 30px !important;
}
.el_video_img {
  position: absolute;
  width: 16px;
  height: 16px;
  cursor: pointer;
  z-index: 99;
  left: 16px;
  bottom: 14px;
}
</style>
